#include "../header/Client.h"

ConnectInfo *Client::info = nullptr;

Client::~Client() = default;

void Client::startClient() {
    info = connectSever();

    if (info == nullptr) {
        getchar();
        system("pause");
        pthread_exit(nullptr);
    }
}

void Client::endClient() {
    close(info->client_fd);
}

int Client::getUserId() {
    // 向服务器获取新用户ID
    int userId = -1;

    if (info != nullptr) {
        string msg = "Get:UserID!";
        string userIdString = sendMsgToSever(msg);

        if (!userIdString.empty()) {
            userId = atoi(userIdString.c_str());
        }
    }

    return userId;
}

ConnectInfo *Client::connectSever() {
    // 1.创建通信的套接字
    int client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (client_fd == -1) {
        perror("Socket Create Fail!\n");
        return nullptr;
    }

    // 2.连接服务器
    struct sockaddr_in server_address;
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &server_address.sin_addr.s_addr);
    int ret = connect(client_fd, (struct sockaddr *) &server_address, sizeof(server_address));
    if (ret == -1) {
        close(client_fd);
        printf("Connect Server Fail!\n");
        return nullptr;

    } else {
        printf("Connect Server Success!\n");
    }

    return new ConnectInfo(client_fd, server_address);
}

string Client::sendMsgToSever(string msg) {
    char buffer[1024];
    sprintf(buffer, "%s", NetworkTools::encryptionMessage(msg).c_str());
    send(info->client_fd, buffer, sizeof(buffer), 0);

    memset(buffer, 0, 1024);

    int length = recv(info->client_fd, buffer, sizeof(buffer), 0);

    if (0 < length) {
        string public_key = buffer;
        string message = NetworkTools::decryptionMessage(public_key);

        return message;

    } else {
        return "";
    }
}